package com.glodon.paas.job.monitor.service;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.glodon.paas.job.model.AlarmConfig;
import com.glodon.paas.job.model.AlarmInfo;
import com.glodon.paas.job.monitor.dao.AlarmDAO;

@Service
public class AlarmService {
    private static final Logger logger = LoggerFactory.getLogger(AlarmService.class);

    @Autowired
    private AlarmDAO alarmDAO;
    
    @Autowired
    private AlarmSchedule alarmSchedule;

    public void processAlarmConfig(AlarmConfig alarmConfig) {
        AlarmConfig config=new AlarmConfig();
        List<AlarmConfig> list = alarmDAO.getAllConfig();
        if(list.isEmpty()){
        	 alarmDAO.save(alarmConfig);
        }else{
        	config = list.get(0);
        	config.setAgentThreshold(alarmConfig.getAgentThreshold());
        	config.setFailureRateTheshold(alarmConfig.getFailureRateTheshold());
        	config.setFaliureTrigger(alarmConfig.isFaliureTrigger());
        	config.setUnProcessThreshold(alarmConfig.getUnProcessThreshold());
        	config.setWaitingTimeThreshold(alarmConfig.getWaitingTimeThreshold());
        	config.setServiceThreshold(alarmConfig.getServiceThreshold());
        	config.setSendTo(alarmConfig.getSendTo());
        	config.setHealthUrl(alarmConfig.getHealthUrl());
        	alarmDAO.save(config);
        }
       
    }
    public void saveAlarmInfo(AlarmInfo alarmInfo){
    	alarmDAO.save(alarmInfo);
    }
    
    public List<AlarmInfo> getAlarmInfoNumMinutes(String alarmDetail){
    	return alarmDAO.getAlarmInfoNumMinutes(alarmDetail);
    }
    
    public AlarmConfig getConfig(){
    	 List<AlarmConfig> list = alarmDAO.getAllConfig();
    	 if(list.isEmpty()){
    		 return new AlarmConfig();
    	 }else{
    		 return list.get(0);
    	 }
    }
    
    public boolean checkServerHealth(AlarmConfig config){
    	return alarmSchedule.checkServiceHealth(config);
    }
    
    public List<AlarmInfo> getAlarmInfo(){
    	return alarmDAO.getAlarmInfo();
    }
    public List<AlarmInfo> getAlarmInfoForPage(int fromNum,int pageNum){
    	return alarmDAO.getAlarmInfoForPage(fromNum,pageNum);
    }
    public List<AlarmInfo> getUnNotifiedAlarmInfo(){
    	return alarmDAO.getUnNotifiedAlarmInfo();
    }
	public AlarmDAO getAlarmDAO() {
		return alarmDAO;
	}
	public void setAlarmDAO(AlarmDAO alarmDAO) {
		this.alarmDAO = alarmDAO;
	}
	public AlarmSchedule getAlarmSchedule() {
		return alarmSchedule;
	}
	
	public void setAlarmSchedule(AlarmSchedule alarmSchedule) {
		this.alarmSchedule = alarmSchedule;
	}
	
}
